package com.navinfo.parkingnavi.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mapbox.mapboxsdk.geometry.LatLng;
import com.navinfo.parkingnavi.Adapter.SearPoiAutoAdapter;
import com.navinfo.parkingnavi.R;
import com.navinfo.parkingnavi.system.SystemConfig;
import com.navinfo.parkingnavi.system.UrlManager;
import com.navinf.parkingnavi.util.FragmentsManager;
import com.navinfo.parkingnavi.util.GsonManager;
import com.navinfo.parkingnavi.util.NetManager;
import com.navinfo.parkingnavi.util.SystemUtil;
import com.navinfo.parkingnavi.util.mode.Poi;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/*
 *com.navinfo.parkingnavi.fragment
 *zhjch
 *2020/5/12
 *9:48
 *说明（关键字搜索页面）
 */
public class SearchFragment extends BaseFragment implements View.OnClickListener {
    /*
     *   输入框
     */
    private EditText mEditText;
    /**
     * 返回按钮
     */
    private View mBack;

    /**
     * 清除按钮
     */
    private View mClear;

    /**
     * 网络请求
     */
    private Call mCall;
    /**
     * 联想查询时间
     */
    private final int handler_PoiAuto = 1;
    /**
     * poi展示列表
     */
    private RecyclerView mRecyclerView;
    /**
     * poi列表适配器
     */
    private SearPoiAutoAdapter mAdapter;
    /**
     * 搜素按钮
     */
    private View mSearchBtn;
    /**
     * 当前城市编码
     */
    private String mCityCode = null;
    /**
     * 要搜索的中心poi点
     */
    private Poi mCenterPoi = null;

    @Override
    public void onDataChange(Bundle bundle) {
        if (bundle != null) {
            //获取屏幕中心点
            Parcelable parcelable = bundle.getParcelable(SystemConfig.Bundle_key_latlng);
            if (parcelable != null && parcelable instanceof LatLng) {
                //获取逆地理编码
                NetManager.getInstance().getData(UrlManager.getRGeoCodeUrl(((LatLng) parcelable).getLatitude(), ((LatLng) parcelable).getLongitude()), new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //解析城市编码
                        mCityCode = GsonManager.getInstance().parseCityCode(response.body().string());
                    }
                });
                return;
            }
            //获取poi
            Serializable serializable = bundle.getSerializable(SystemConfig.Bundle_key_poi);
            if (serializable != null && serializable instanceof Poi) {
                mCenterPoi = (Poi) serializable;
                mCityCode = mCenterPoi.getCityadcode();
                String poiName = mCenterPoi.getName_zh();
                if (poiName.length() > 10) {
                    poiName = poiName.substring(0, 10) + "...";
                }
                mEditText.setHint("在 " + poiName + " 附近搜索");
            }
        }
    }


    /*
     * 让activity监听
     */
    public interface OnSearchFragmentListener extends OnBaseFragmentListener {
        void onSearchResult(String key, Poi centerPoi, String cityCode, ArrayList<Poi> list);

        //显示搜索道德poi
        void onShowPoi(Poi poi);

        //显示周边搜索结果
        void onShowNearPoi(Poi centerPoi, Poi nearPoi);

        void onShowRoute(Poi poi);
    }


    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == handler_PoiAuto) {
                if (mCall != null && mCall.isExecuted()) {
                    mCall.cancel();
                    mCall = null;
                }
                String url;
                if (mCenterPoi != null) {
                    url = UrlManager.getNearPoiListUrl(String.valueOf(msg.obj), mCenterPoi.getLon(), mCenterPoi.getLat(), mCityCode, 1);
                } else {
                    if (mCityCode != null)
                        url = UrlManager.getPoiSearchUrl(String.valueOf(msg.obj), mCityCode, 1, 10);
                    else
                        url = UrlManager.getPoiSearchUrl(String.valueOf(msg.obj), 1, 10);
                }
                mCall = NetManager.getInstance().getData(url, new okhttp3.Callback() {

                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d("jingo", "onFailure: " + e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response != null && response.body() != null) {
                            final ArrayList<Poi> list = GsonManager.getInstance().parsePoiList(response.body().string());

                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (list != null && list.size() > 0)
                                        mAdapter.setData(list);
                                }
                            });
                        }
                    }
                });
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mFragmentView = inflater.inflate(R.layout.fragment_search, null);

        //输入框自动获取焦点，弹出键盘
        mEditText = mFragmentView.findViewById(R.id.search_input);
        mEditText.setFocusable(true);
        mEditText.setFocusableInTouchMode(true);
        mEditText.requestFocus();
        //自动显示键盘
        SystemUtil.showKeyBoard(getActivity(), mEditText);
        //监听输入框输入情况
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() != 0 && s.toString().trim().length() != 0) {

                    if (mHandler.hasMessages(handler_PoiAuto)) {
                        mHandler.removeMessages(handler_PoiAuto);
                    }
                    Message msg = Message.obtain();
                    msg.what = handler_PoiAuto;
                    msg.obj = s.toString(); //携带当前值
                    mHandler.sendMessageDelayed(msg, 500);

                } else {
                    if (mHandler.hasMessages(handler_PoiAuto)) {
                        mHandler.removeMessages(handler_PoiAuto);
                    }
                }
            }
        });

        mSearchBtn = mFragmentView.findViewById(R.id.search_btn);
        mSearchBtn.setOnClickListener(this);

        mBack = mFragmentView.findViewById(R.id.search_back);
        mBack.setOnClickListener(this);

        mClear = mFragmentView.findViewById(R.id.search_clear);
        mClear.setOnClickListener(this);

        mRecyclerView = mFragmentView.findViewById(R.id.search_recyclerview);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //滑动时关闭输入框
                SystemUtil.hideKeyBoard(getActivity(), mEditText);
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new SearPoiAutoAdapter();
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.addOnItemClickListener(new SearPoiAutoAdapter.OnItemClickListener() {
            @Override
            public void onShowPoi(Poi poi) {
                if (mListener != null && mListener instanceof OnSearchFragmentListener) {
                    if (mCenterPoi != null) {
                        ((OnSearchFragmentListener) mListener).onShowNearPoi(mCenterPoi, poi);
                    } else {
                        ((OnSearchFragmentListener) mListener).onShowPoi(poi);
                    }

                }
            }

            @Override
            public void onShowNavi(Poi poi) {
                if(mListener != null && mListener instanceof OnSearchFragmentListener){
                    ((OnSearchFragmentListener) mListener).onShowRoute(poi);
                }
            }
        });

        return mFragmentView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_back:
                //隐藏键盘
                FragmentsManager.getInstance().onBackPressed();
                break;
            case R.id.search_clear:
                //清空文字
                mEditText.setText("");
                break;
            case R.id.search_btn:
                ArrayList<Poi> list = mAdapter.getData();
                if (list != null && list.size() > 0 && mListener != null && mListener instanceof OnSearchFragmentListener) {
                    ((OnSearchFragmentListener) mListener).onSearchResult(mEditText.getText().toString(), mCenterPoi, mCityCode, list);
                }
                break;
        }
    }


    @Override
    public void onDestroyView() {
        SystemUtil.hideKeyBoard(getActivity(), mEditText);
        if (mCall != null && mCall.isExecuted()) {
            mCall.cancel();
            mCall = null;
        }
        super.onDestroyView();
    }
}
